<template>
  <el-dialog v-model="open" title="添加数据" width="600px" @open="openForm" @close="closeBtn">
    <el-form :model="form" ref="formRef" label-width="100px" :rules="rules" scroll-to-error>
      <el-form-item label="数据类别：" prop="typeCode">
        <el-select v-model="form.typeCode" clearable>
          <el-option v-for="item in codeOption" :key="item.tableName" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据文件：" prop="fileIds">
        <file-upload v-model="form.fileList" :limit="1000" uploadUrl="/attachment/uploadShpFile"
          downloadUrl="/attachment/downLoadShpFile" @uploadFile="uploadSuccess" @delFile="delFile"></file-upload>
      </el-form-item>
      <el-form-item label="上传人：" prop="uploadUser">
        <span>{{ form.uploadUser }}</span>
      </el-form-item>
      <el-form-item label="上传日期：" prop="extends1">
        <span>{{ form.extends1 }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="saveBtn">保存</el-button>
      <el-button type="primary" @click="resetBtn">清空</el-button>
      <el-button plain @click="closeBtn">取消</el-button>
    </template>
  </el-dialog>

  <el-collapse-transition>
    <el-card v-if="isShowList" class="upload-card">
      <p>
        <el-row :gutter="10" justify="space-between">
          <el-col :span="21" class="form-name">{{ formName }}数据</el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="saveList">确定</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button plain @click="isShowList = false">关闭</el-button>
          </el-col>
        </el-row>
      </p>
      <el-table v-loading="uploadTableLoading" :data="uploadTable" :border="true" stripe max-height="300">
        <el-table-column v-for="item in uploadTableName" :key="item" :label="item.name" :prop="item.title" align="center"
          :min-width="minWidthSet(item.name)">
          <template #default="{ row }" v-if="checkDict(item.title, typeCode)">
            <dict-tag :value="row[item.title]" :code="checkDict(item.title, typeCode)"></dict-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </el-collapse-transition>
</template>
<script setup>
import { useNow, useDateFormat } from '@vueuse/core'
import { getList, isEmpty, parseShp, saveShp } from '@/api/quickMapping/dataManage/dataManage'
import { minWidthSet } from '@/views/businessManage/common/minWidth'
import { checkDict } from '@/views/businessManage/common/dict'

const props = defineProps({
  open: Boolean
})
const emits = defineEmits(['update:open'])
const { proxy } = getCurrentInstance()

const initForm = () => {
  return {
    typeCode: '',
    uploadUser: localStorage.getItem('userName'),
    extends1: useDateFormat(useNow(), 'YYYY-MM-DD').value
  }
}
const form = reactive(initForm())
const rules = {
  typeCode: [{ required: true, message: '请选择数据类别！', trigger: 'change' }],
  fileIds: [{ required: true, message: '请上传数据文件！' }]
}
const codeOption = ref([])

const uploadSuccess = (files) => {
  form.fileIds = files.map(item => item.attachId).join(',')
  form.fileList = files
  proxy.$refs['formRef'].clearValidate()
}
const delFile = files => {
  form.fileIds = files.map(item => item.attachId).join(',')
}
const openForm = () => {
  nextTick(() => {
    proxy.$refs['formRef'].clearValidate()
  })
  getTypeCode()
}
// 获取数据类别
const getTypeCode = () => {
  getList().then(res => {
    codeOption.value = res.data
  })
}
const uploadTableName = ref({})
const formName = ref('')
const uploadTable = ref([])
const isShowList = ref(false)
const uploadTableLoading = ref(false)
const typeCode = ref('')
const saveBtn = () => {
  proxy.$refs['formRef'].validate(async valid => {
    if (valid) {
      typeCode.value = form.typeCode
      let tableName = codeOption.value.find(item => item.code == form.typeCode)?.tableName
      let res = await isEmpty({ tableName })
      uploadTableLoading.value = true
      if (res.data == '1') {
        proxy.$modal.confirm('该数据类别下已有该数据，是否进行覆盖？').then(function () {
          return parseShp(form)
        }).then(res => {
          proxy.$modal.msgSuccess('覆盖成功！')
          uploadTable.value = res.data.list
          uploadTableName.value = res.data.titleAndNameVOS
          formName.value = res.data.formName
          if (uploadTable.value.length > 0) { isShowList.value = true }
          emits('update:open', false)
          uploadTableLoading.value = false
          resetBtn()
        })
      } else {
        parseShp(form).then(res => {
          proxy.$modal.msgSuccess('保存成功！')
          uploadTable.value = res.data.list
          uploadTableName.value = res.data.titleAndNameVOS
          formName.value = res.data.formName
          if (uploadTable.value.length > 0) { isShowList.value = true }
          emits('update:open', false)
          uploadTableLoading.value = false
          resetBtn()
        })
      }
    }
  })
}
const resetBtn = () => {
  proxy.resetAllForm(form, initForm())
}
const closeBtn = () => {
  resetBtn()
  emits('update:open', false)
}
// 确定
const saveList = () => {
  saveShp(typeCode.value, uploadTable.value).then(res => {
    proxy.$modal.msgSuccess('添加成功！')
    isShowList.value = false
  })
}
defineExpose({
  isShowList
})
</script>
<style scoped lang="scss">
.upload-card{
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 10;
}
</style>